<template>
  <XtxDialog v-model:visible="visibleDialog" title="取消订单">
    <!-- 取消订单列表 -->
    <template v-slot:body>
      <div class="cancel-info">
        <p>取消订单后，本单享有的优惠可能会一并取消，是否继续？</p>
        <p class="tip">请选择取消订单的原因（必选）:</p>
        <div class="btn">
          <a v-for="(item, i) in cancelReason"
             :key="i"
             :class="{active: curText === item}"
             href="javascript:;"
             @click="curText = item">{{ item }}</a>
        </div>
      </div>
    </template>

    <template v-slot:footer>
      <XtxButton style="margin-right: 20px" type="gray" @click="visibleDialog = false">取消</XtxButton>
      <XtxButton type="primary" @click="submit">确认</XtxButton>
    </template>
  </XtxDialog>
</template>

<script>
import { cancelReason } from '@/constant'
// 订单取消组件
import XtxDialog from '@/components/library/XtxDialog'
import { ref } from 'vue'
import API from '@/api/order'
import Message from '@/components/library/Message'

export default {
  name: 'OrderCancel',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  components: { XtxDialog },
  setup() {
    // 显示状态
    const visibleDialog = ref(false)
    // 选中的原因label
    const curText = ref('')

    const curOrder = ref(null)

    /**
     * 打开对话框
     * @param order 订单信息
     */
    const open = (order) => {
      visibleDialog.value = true
      curOrder.value = order
    }

    const submit = () => {
      // 发送取消订单请求
      if (curText.value === '') {
        return Message({ text: '亲, 请选择取消原因' })
      }
      API.orderCancel(curOrder.value.id, curText.value)
          .then((res) => {
            Message({
              type: 'success',
              text: '取消订单成功'
            })
            // 更新该商品的状态
            curOrder.value.orderState = 6
            // 关闭弹出框
            visibleDialog.value = false
          })
          .catch((err) => {
            Message({
              text: `取消订单失败, ${err.response.data.message}`
            })
          })
    }

    return {
      visibleDialog,
      cancelReason,
      submit,
      curText,
      open
    }
  }
}
</script>

<style lang="less" scoped>
// 注意不能写成这样, 不然样式改不了, 最终改的样式还是 .wrapper的宽度
//::v-deep .xtx-dialog{
//  .wrapper{
//    width: 620px;
//  }
//}

.xtx-dialog {
  ::v-deep .wrapper {
    width: 620px;
  }
}

.cancel-info {
  p {
    height: 35px;
    line-height: 35px;

    font-size: 16px;

    &.tip {
      color: #999;
    }
  }

  .btn {
    display: flex;
    flex-wrap: wrap;
    margin-top: 20px;
    text-align: center;

    a {
      width: 256px;
      height: 45px;
      line-height: 45px;
      margin-bottom: 20px;
      margin-right: 20px;

      color: #666;
      background-color: #fff;
      border: 1px solid #e4e4e4;
      border-radius: 3px;

      &:nth-child(2n) {
        margin-right: 0;
      }

      &:hover, &.active {
        background-color: #e3f9f4;
        border-color: @xtxColor;
      }
    }
  }
}
</style>
